import React, { Suspense } from "react";
import {
  BrowserRouter as Router,
  Routes,
  Route,
  Navigate,
} from "react-router-dom";
import { ConfigProvider, Spin, message } from "antd";
import zhCN from "antd/locale/zh_CN";
import { AuthProvider, useAuth } from "./contexts/AuthContext";
import { WebSocketProvider } from "./contexts/WebSocketContext";
import Layout from "./layouts/MainLayout";
import Login from "./pages/Login";
import "./App.css";

// 路由保护组件
const ProtectedRoute: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => {
  const { state } = useAuth();

  if (state.loading) {
    return (
      <div
        style={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          height: "100vh",
        }}
      >
        <Spin size="large" tip="加载中..." />
      </div>
    );
  }

  if (!state.isAuthenticated) {
    return <Navigate to="/login" replace />;
  }

  return <>{children}</>;
};

// 应用路由组件
const AppRoutes: React.FC = () => {
  const { state } = useAuth();

  return (
    <Routes>
      <Route
        path="/login"
        element={
          state.isAuthenticated ? (
            <Navigate to="/dashboard" replace />
          ) : (
            <Login />
          )
        }
      />

      <Route path="/" element={<Navigate to="/dashboard" replace />} />

      <Route
        path="/*"
        element={
          <ProtectedRoute>
            <Layout />
          </ProtectedRoute>
        }
      />
    </Routes>
  );
};

// 主应用组件
const App: React.FC = () => {
  // 全局错误处理
  React.useEffect(() => {
    const handleError = (event: ErrorEvent) => {
      console.error("全局错误:", event.error);
      message.error("系统发生错误，请刷新页面重试");
    };

    const handleUnhandledRejection = (event: PromiseRejectionEvent) => {
      console.error("未处理的Promise拒绝:", event.reason);
      message.error("网络请求失败，请检查网络连接");
    };

    window.addEventListener("error", handleError);
    window.addEventListener("unhandledrejection", handleUnhandledRejection);

    return () => {
      window.removeEventListener("error", handleError);
      window.removeEventListener(
        "unhandledrejection",
        handleUnhandledRejection
      );
    };
  }, []);

  // 配置主题
  const theme = {
    token: {
      colorPrimary: "#1890ff",
      borderRadius: 6,
      colorSuccess: "#52c41a",
      colorWarning: "#fa8c16",
      colorError: "#ff4d4f",
      fontSize: 14,
      fontFamily:
        '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif',
    },
    components: {
      Layout: {
        headerBg: "#fff",
        siderBg: "#001529",
        bodyBg: "#f0f2f5",
      },
      Menu: {
        darkItemBg: "#001529",
        darkSubMenuItemBg: "#000c17",
        darkItemSelectedBg: "#1890ff",
      },
      Card: {
        borderRadius: 8,
        boxShadowCard:
          "0 1px 2px -2px rgba(0, 0, 0, 0.16), 0 3px 6px 0 rgba(0, 0, 0, 0.12), 0 5px 12px 4px rgba(0, 0, 0, 0.09)",
      },
      Button: {
        borderRadius: 6,
      },
      Input: {
        borderRadius: 6,
      },
    },
  };

  return (
    <ConfigProvider
      locale={zhCN}
      theme={theme}
      form={{
        validateMessages: {
          required: "${label}是必填项",
          types: {
            email: "${label}格式不正确",
            number: "${label}必须是数字",
          },
          number: {
            range: "${label}必须在${min}-${max}之间",
          },
        },
      }}
    >
      <Router>
        <AuthProvider>
          <WebSocketProvider>
            <div className="app">
              <AppRoutes />
            </div>
          </WebSocketProvider>
        </AuthProvider>
      </Router>
    </ConfigProvider>
  );
};

export default App;
